from django.shortcuts import render, render_to_response
from .models import User,Article
from django.http import HttpResponse, HttpResponseRedirect
import json,os,time
import AskShare.Constants
from app.forms import ArticleForm,RegisterForm

from django.template import loader
# Create your views here.
# Create your views here.

from django.shortcuts import render_to_response,render,get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from app.models import User
from django.contrib import auth
from django.contrib import messages
from django.template.context import RequestContext
from captcha import urls
from django.forms.formsets import formset_factory
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage

from bootstrap_toolkit.widgets import BootstrapUneditableInput
from django.contrib.auth.decorators import login_required

from django.http import JsonResponse

from app.forms import LoginForm
import captcha
# from captcha.models import CaptchaStore
# from captcha.helpers import captcha_image_url
# hashkey = CaptchaStore.generate_key()
# imgage_url = captcha_image_url(hashkey)

def login(request):
    if request.method == 'GET':
        form = LoginForm()

        #html = template.render(context=locals(), request=request)
        #html=get_template('login.html')
        #return html
        #return HttpResponse(html)
        context = {'form': form}
        return render(request, 'login.html', context)
        #return render_to_response('login.html',RequestContext(request,{'form':form,}))
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            username = request.POST.get('username','')
            password = request.POST.get('password','')
            user = auth.authenticate(username=username,password=password)
            if user is not None and user.is_active:
                auth.login(request,user)
                return render_to_response('index.html',RequestContext(request))
            else:
                return render_to_response('login.html',RequestContext(request,{'form':form,'password_is_wrong':True}))
        else:
            return render_to_response('login.html',RequestContext(request,{'form':form,}))
def index(request):
    user_ = User()
    user_.name='Guo'
    context = {'user_': user_}
    # return render(request, 'app/index.html', context)
    return render(request, 'app/index.html')

def home(request):
    return render(request, 'app/index.html')

# def login(request):
#     return render(request, 'app/login.html')

def register(request):
    form = RegisterForm()
    context = {'form': form}
    if request.method == 'GET':
        return render(request, 'app/register.html', context)
    else:
        form = RegisterForm(request.POST)
        # print(form.cleaned_data)
        context = {'form': form}
        username = request.POST.get('username','')
        password1 = request.POST.get('password1','')
        password2 = request.POST.get('password2','')
        if password2==password2:

            pass
        if form.is_valid():
            print(dict)
            # del (dict)
            form.cleaned_data()
            user = auth.authenticate(username=username,password=password1)
            if user is not None and user.is_active:
                auth.login(request,user)
                return render_to_response('index.html',RequestContext(request))
            else:
                return render_to_response('login.html',RequestContext(request,{'form':form,'password_is_wrong':True}))
        else:
            return render(request, 'app/register.html', context)

def layout(request):
    return render(request, 'exlayout.html')

def publishask(request):
    if request.method=="GET":
        return render(request, 'app/publishask.html')
    else:
        form =ArticleForm(request.POST)
        # print(form.title+'    '+form.content )
        print(request.POST['title']+'    '+request.POST['content'])
        if form.is_valid():
            var = form.clean()
            article=Article()
            try:
                article.createdate=time.localtime()
                article.title=request.POST['title'];
                article.content=request.POST['content']
                article.deposit=False#request.POST['deposit']
                article.Money_reward=request.POST['Money_reward']
                article.status=0#request.POST['status']
                article.author='admin'#request.POST['author']
                article.type=0#request.POST['type']
            except Exception as ex:
                print(ex)
                pass
            pass
        else:
            # error_msg = form.errors.as_json().decode('unicode_escape')
            error_msg = form.errors.as_json().encode('utf-8','ignore').decode('unicode_escape')
            print(error_msg)
            return render(request, 'app/publishask.html',{"form":form,"err":error_msg})
            pass
    pass

def uploadfle(request):
    # 拿到文件，保存在指定路径
    #print(request.FILES)  # {'imgFile': [<InMemoryUploadedFile: QQ图片20170523192846.jpg (image/jpeg)>]}
    imgFile = request.FILES.get('imgFile')  # 拿到文件对象，imgFile.name, 拿到文件名

    allow_suffix = ['jpg', 'png', 'jpeg', 'gif', 'bmp']
    file_suffix = imgFile.name.split(".")[-1]
    if file_suffix not in allow_suffix:
        return {"error": 1, "message": "图片格式不正确"}

    try:
        dt = time.localtime()
        path = time.strftime(AskShare.Constants.imageFilePath, dt)

        if os.path.exists(path) == False:
            os.makedirs(path)
            pass
        name = path + '/'+time.strftime("%Y%m%d%H%M%S", dt)+imgFile.name
        with open(name, 'wb')as f:  # with open 无法创建文件夹，需要自己创建
            for chunk in imgFile.chunks():
                f.write(chunk)  # 返回json响应
    except Exception as err:
        print(err)
        pass
    print(name)
    response = {
        'error': 0, 'url': name
    # 客户端拿到路径，才能预览图片; media在setting中配置了别名，这里只写media，客户端就可以找到路径，前面不需要加/app
    }
    return HttpResponse(json.dumps(response))

# 刷新验证码
def refresh_captcha(request):
    to_json_response = dict()
    to_json_response['status'] = 1
    to_json_response['new_cptch_key'] = captcha.models.CaptchaStore.generate_key()
    to_json_response['new_cptch_image'] = captcha.helpers.captcha_image_url(to_json_response['new_cptch_key'])
    return HttpResponse(json.dumps(to_json_response), content_type='application/json')
def ajax_val(request):
    if  request.is_ajax():
        cs = captcha.models.CaptchaStore.objects.filter(response=request.GET['response'], hashkey=request.GET['hashkey'])
        if cs:
            json_data={'status':1}
        else:
            json_data = {'status':0}
        return JsonResponse(json_data)
    else:
        # raise Http404
        json_data = {'status':0}
        return JsonResponse(json_data)
